
<!DOCTYPE HTML>
<html lang="" >
    <head>
        <meta charset="UTF-8">
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <title>解决ajax跨域问题【5种解决方案】 · GitBook</title>
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="description" content="">
        <meta name="generator" content="GitBook 3.2.3">
        
        
        
    
    <link rel="stylesheet" href="../gitbook/style.css">

    
            
                
                <link rel="stylesheet" href="../gitbook/gitbook-plugin-highlight/website.css">
                
            
                
                <link rel="stylesheet" href="../gitbook/gitbook-plugin-search/search.css">
                
            
                
                <link rel="stylesheet" href="../gitbook/gitbook-plugin-fontsettings/website.css">
                
            
        

    

    
        
    
        
    
        
    
        
    
        
    
        
    

        
    
    
    <meta name="HandheldFriendly" content="true"/>
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <link rel="apple-touch-icon-precomposed" sizes="152x152" href="../gitbook/images/apple-touch-icon-precomposed-152.png">
    <link rel="shortcut icon" href="../gitbook/images/favicon.ico" type="image/x-icon">

    
    <link rel="next" href="解决vue-cli webpack打包后加载资源的路径问题.html" />
    
    
    <link rel="prev" href="获取当前地址坐标.html" />
    

    </head>
    <body>
        
<div class="book">
    <div class="book-summary">
        
            
<div id="book-search-input" role="search">
    <input type="text" placeholder="Type to search" />
</div>

            
                <nav role="navigation">
                


<ul class="summary">
    
    

    

    
        
        
    
        <li class="chapter " data-level="1.1" data-path="../">
            
                <a href="../">
            
                    
                    Introduction
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.2" data-path="../cmd命令.html">
            
                <a href="../cmd命令.html">
            
                    
                    cmd命令
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.3" data-path="Array.prototype.slice.call.html">
            
                <a href="Array.prototype.slice.call.html">
            
                    
                    Array.prototype.slice.call解析
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.4" data-path="async 函数.html">
            
                <a href="async 函数.html">
            
                    
                    async 函数
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5" data-path="callback&&callback如果存在回调函数就执行.html">
            
                <a href="callback&&callback如果存在回调函数就执行.html">
            
                    
                    callback&&callback() 如果存在回调函数就执行！
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.6" data-path="CSS3 nth-child使用注意.html">
            
                <a href="CSS3 nth-child使用注意.html">
            
                    
                    CSS3 nth-child(n)使用注意
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.7" data-path="css3的 -webkit-min-device-pixel-ratio属性 解决高清的适配.html">
            
                <a href="css3的 -webkit-min-device-pixel-ratio属性 解决高清的适配.html">
            
                    
                    css3的 -webkit-min-device-pixel-ratio属性 解决高清的适配
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.8" data-path="CSS文本超出自动缩小字体.html">
            
                <a href="CSS文本超出自动缩小字体.html">
            
                    
                    CSS文本超出自动缩小字体
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.9" data-path="element-ui默认样式修改.html">
            
                <a href="element-ui默认样式修改.html">
            
                    
                    element-ui默认样式修改
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.10" data-path="JavaScript setInterval函数详解.html">
            
                <a href="JavaScript setInterval函数详解.html">
            
                    
                    JavaScript setInterval() 函数详解
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.11" data-path="JavaScript概念之screenclientoffsetscrollinneravail的widthleft.html">
            
                <a href="JavaScript概念之screenclientoffsetscrollinneravail的widthleft.html">
            
                    
                    JavaScript概念之screenclientoffsetscrollinneravail的widthleft
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.12" data-path="js获取星期几.html">
            
                <a href="js获取星期几.html">
            
                    
                    js获取星期几
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.13" data-path="js监听滚动条事件和获取浏览器及屏幕高度和宽度等信息的方法.html">
            
                <a href="js监听滚动条事件和获取浏览器及屏幕高度和宽度等信息的方法.html">
            
                    
                    js监听滚动条事件和获取浏览器及屏幕高度和宽度等信息的方法
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.14" data-path="js时间戳与日期格式之间相互转换.html">
            
                <a href="js时间戳与日期格式之间相互转换.html">
            
                    
                    js时间戳与日期格式之间相互转换
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.15" data-path="JS数组reduce方法详解及高级技巧.html">
            
                <a href="JS数组reduce方法详解及高级技巧.html">
            
                    
                    JS数组reduce()方法详解及高级技巧
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.16" data-path="js中获取时间new Date详细介绍.html">
            
                <a href="js中获取时间new Date详细介绍.html">
            
                    
                    js中获取时间new Date()详细介绍
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.17" data-path="less传参问题：在url中插入变量今天在需要用less给url传递参数时遇到了小问题，一番搜索后有了下述解决方法.html">
            
                <a href="less传参问题：在url中插入变量今天在需要用less给url传递参数时遇到了小问题，一番搜索后有了下述解决方法.html">
            
                    
                    less传参问题：在url中插入变量今天在需要用less给url传递参数时遇到了小问题，一番搜索后有了下述解决方法
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.18" data-path="moment 和date-fns.html">
            
                <a href="moment 和date-fns.html">
            
                    
                    moment 和date-fns
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.19" data-path="node.JS中配置http-server.html">
            
                <a href="node.JS中配置http-server.html">
            
                    
                    node.JS中配置http-server
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.20" data-path="Object.keys详解.html">
            
                <a href="Object.keys详解.html">
            
                    
                    Object.keys详解
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.21" data-path="router-link各种属性解释.html">
            
                <a href="router-link各种属性解释.html">
            
                    
                    router-link各种属性解释
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.22" data-path="stylus使用介绍.html">
            
                <a href="stylus使用介绍.html">
            
                    
                    stylus使用介绍
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.23" data-path="TypeError Cannot read property 'compilation' of undefined.html">
            
                <a href="TypeError Cannot read property 'compilation' of undefined.html">
            
                    
                    TypeError Cannot read property 'compilation' of undefined
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.24" data-path="Vue  keep-alive.html">
            
                <a href="Vue  keep-alive.html">
            
                    
                    Vue  keep-alive
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.25" data-path="Vue - 过渡与动画transition.html">
            
                <a href="Vue - 过渡与动画transition.html">
            
                    
                    Vue - 过渡与动画transition
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.26" data-path="vue-axios使用方法.html">
            
                <a href="vue-axios使用方法.html">
            
                    
                    vue-axios使用方法
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.27" data-path="vue-calendar-component.html">
            
                <a href="vue-calendar-component.html">
            
                    
                    vue-calendar-component
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.28" data-path="vue-infinite-loading.html">
            
                <a href="vue-infinite-loading.html">
            
                    
                    vue-infinite-loading
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.29" data-path="vue报错There are multiple modules with names that only differ in casing.html">
            
                <a href="vue报错There are multiple modules with names that only differ in casing.html">
            
                    
                    vue报错There are multiple modules with names that only differ in casing
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.30" data-path="Vue中注意target和currentTarget的使用.html">
            
                <a href="Vue中注意target和currentTarget的使用.html">
            
                    
                    Vue中注意target和currentTarget的使用
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.31" data-path="关于给javascript对象添加、删除、修改对象的属性.html">
            
                <a href="关于给javascript对象添加、删除、修改对象的属性.html">
            
                    
                    关于给javascript对象添加、删除、修改对象的属性
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.32" data-path="获取当前地址坐标.html">
            
                <a href="获取当前地址坐标.html">
            
                    
                    获取当前地址坐标
            
                </a>
            

            
        </li>
    
        <li class="chapter active" data-level="1.33" data-path="解决ajax跨域问题【5种解决方案】.html">
            
                <a href="解决ajax跨域问题【5种解决方案】.html">
            
                    
                    解决ajax跨域问题【5种解决方案】
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.34" data-path="解决vue-cli webpack打包后加载资源的路径问题.html">
            
                <a href="解决vue-cli webpack打包后加载资源的路径问题.html">
            
                    
                    解决vue-cli webpack打包后加载资源的路径问题
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.35" data-path="时间格式转换：201971转换为2019-7-1.html">
            
                <a href="时间格式转换：201971转换为2019-7-1.html">
            
                    
                    时间格式转换：201971转换为2019-7-1
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.36" data-path="数据库密码改了.html">
            
                <a href="数据库密码改了.html">
            
                    
                    数据库密码改了
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.37" data-path="语法getBoundingClientRect.html">
            
                <a href="语法getBoundingClientRect.html">
            
                    
                    语法getBoundingClientRect()
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.38" data-path="在js中使用length报错Error in renderTypeErrorcannot read property bgImg of null.html">
            
                <a href="在js中使用length报错Error in renderTypeErrorcannot read property bgImg of null.html">
            
                    
                    在js中使用length报错Error in renderTypeErrorcannot read property bgImg of null
            
                </a>
            

            
        </li>
    

    

    <li class="divider"></li>

    <li>
        <a href="https://www.gitbook.com" target="blank" class="gitbook-link">
            Published with GitBook
        </a>
    </li>
</ul>


                </nav>
            
        
    </div>

    <div class="book-body">
        
            <div class="body-inner">
                
                    

<div class="book-header" role="navigation">
    

    <!-- Title -->
    <h1>
        <i class="fa fa-circle-o-notch fa-spin"></i>
        <a href=".." >解决ajax跨域问题【5种解决方案】</a>
    </h1>
</div>




                    <div class="page-wrapper" tabindex="-1" role="main">
                        <div class="page-inner">
                            
<div id="book-search-results">
    <div class="search-noresults">
    
                                <section class="normal markdown-section">
                                
                                <h1 id="&#x89E3;&#x51B3;ajax&#x8DE8;&#x57DF;&#x95EE;&#x9898;&#x3010;5&#x79CD;&#x89E3;&#x51B3;&#x65B9;&#x6848;&#x3011;">&#x89E3;&#x51B3;ajax&#x8DE8;&#x57DF;&#x95EE;&#x9898;&#x3010;5&#x79CD;&#x89E3;&#x51B3;&#x65B9;&#x6848;&#x3011;</h1>
<p>&#x200B;                                                   2018&#x5E74;09&#x6708;02&#x65E5; 21:31:33           <a href="https://me.csdn.net/itcats_cn" target="_blank">itcats_cn</a>           &#x9605;&#x8BFB;&#x6570; 6042                   </p>
<p>&#x200B;                   </p>
<h2 id="&#x4EC0;&#x4E48;&#x662F;&#x8DE8;&#x57DF;&#x95EE;&#x9898;">&#x4EC0;&#x4E48;&#x662F;&#x8DE8;&#x57DF;&#x95EE;&#x9898;?</h2>
<p>&#x8DE8;&#x57DF;&#x95EE;&#x9898;&#x6765;&#x6E90;&#x4E8E;JavaScript&#x7684;&quot;&#x540C;&#x6E90;&#x7B56;&#x7565;&quot;&#xFF0C;&#x5373;&#x53EA;&#x6709; &#x534F;&#x8BAE;+&#x4E3B;&#x673A;&#x540D;+&#x7AEF;&#x53E3;&#x53F7; (&#x5982;&#x5B58;&#x5728;)&#x76F8;&#x540C;&#xFF0C;&#x5219;&#x5141;&#x8BB8;&#x76F8;&#x4E92;&#x8BBF;&#x95EE;&#x3002;&#x4E5F;&#x5C31;&#x662F;&#x8BF4;JavaScript&#x53EA;&#x80FD;&#x8BBF;&#x95EE;&#x548C;&#x64CD;&#x4F5C;&#x81EA;&#x5DF1;&#x57DF;&#x4E0B;&#x7684;&#x8D44;&#x6E90;&#xFF0C;&#x4E0D;&#x80FD;&#x8BBF;&#x95EE;&#x548C;&#x64CD;&#x4F5C;&#x5176;&#x4ED6;&#x57DF;&#x4E0B;&#x7684;&#x8D44;&#x6E90;&#x3002;&#x8DE8;&#x57DF;&#x95EE;&#x9898;&#x662F;&#x9488;&#x5BF9;JS&#x548C;ajax&#x7684;&#xFF0C;html&#x672C;&#x8EAB;&#x6CA1;&#x6709;&#x8DE8;&#x57DF;&#x95EE;&#x9898;&#x3002;</p>
<p>&#x67E5;&#x770B;&#x6D4F;&#x89C8;&#x5668;&#x5F00;&#x53D1;&#x8005;&#x5DE5;&#x5177;Console&#x62A5;&#x9519;&#xFF1A;</p>
<p>Failed to load <a href="http://a.a.com:8080/A/FromServlet?userName=123" target="_blank">http://a.a.com:8080/A/FromServlet?userName=123</a>: No  &apos;Access-Control-Allow-Origin&apos; header is present on the requested  resource. Origin &apos;<a href="http://b.b.com:8080" target="_blank">http://b.b.com:8080</a>&apos; is therefore not allowed access.</p>
<p><a href="http://www.abc.com/a/b" target="_blank">http://www.abc.com/a/b</a> &#x8C03;&#x7528; <a href="http://www.abc.com/d/c&#xFF08;&#x975E;&#x8DE8;&#x57DF;&#xFF09;" target="_blank">http://www.abc.com/d/c&#xFF08;&#x975E;&#x8DE8;&#x57DF;&#xFF09;</a></p>
<p><a href="http://www.abc.com/a/b" target="_blank">http://www.abc.com/a/b</a> &#x8C03;&#x7528; <a href="http://www.def.com/a/b" target="_blank">http://www.def.com/a/b</a> &#xFF08;&#x8DE8;&#x57DF;&#xFF1A;&#x57DF;&#x540D;&#x4E0D;&#x4E00;&#x81F4;&#xFF09;</p>
<p><a href="http://www.abc.com:8080/a/b" target="_blank">http://www.abc.com:8080/a/b</a> &#x8C03;&#x7528; <a href="http://www.abc.com:8081/d/c" target="_blank">http://www.abc.com:8081/d/c</a> &#xFF08;&#x8DE8;&#x57DF;&#xFF1A;&#x7AEF;&#x53E3;&#x4E0D;&#x4E00;&#x81F4;&#xFF09;</p>
<p><a href="http://www.abc.com/a/b" target="_blank">http://www.abc.com/a/b</a> &#x8C03;&#x7528; <a href="https://www.abc.com/d/c" target="_blank">https://www.abc.com/d/c</a> &#xFF08;&#x8DE8;&#x57DF;&#xFF1A;&#x534F;&#x8BAE;&#x4E0D;&#x540C;&#xFF09;</p>
<p>&#x8BF7;&#x6CE8;&#x610F;&#xFF1A;localhost&#x548C;127.0.0.1&#x867D;&#x7136;&#x90FD;&#x6307;&#x5411;&#x672C;&#x673A;&#xFF0C;&#x4F46;&#x4E5F;&#x5C5E;&#x4E8E;&#x8DE8;&#x57DF;&#x3002;</p>
<h2 id="&#x8DE8;&#x57DF;&#x95EE;&#x9898;&#x600E;&#x4E48;&#x89E3;&#x51B3;&#xFF1F;">&#x8DE8;&#x57DF;&#x95EE;&#x9898;&#x600E;&#x4E48;&#x89E3;&#x51B3;&#xFF1F;</h2>
<p>1&#x3001;&#x54CD;&#x5E94;&#x5934;&#x6DFB;&#x52A0;Header&#x5141;&#x8BB8;&#x8BBF;&#x95EE;</p>
<p>2&#x3001;jsonp &#x53EA;&#x652F;&#x6301;get&#x8BF7;&#x6C42;&#x4E0D;&#x652F;&#x6301;post&#x8BF7;&#x6C42;</p>
<p>3&#x3001;httpClient&#x5185;&#x90E8;&#x8F6C;&#x53D1;</p>
<p>4&#x3001;&#x4F7F;&#x7528;&#x63A5;&#x53E3;&#x7F51;&#x5173;&#x2014;&#x2014;nginx&#x3001;springcloud zuul   (&#x4E92;&#x8054;&#x7F51;&#x516C;&#x53F8;&#x5E38;&#x89C4;&#x89E3;&#x51B3;&#x65B9;&#x6848;)</p>
<h3 id="&#x89E3;&#x51B3;&#x65B9;&#x5F0F;1&#xFF1A;&#x54CD;&#x5E94;&#x5934;&#x6DFB;&#x52A0;header&#x5141;&#x8BB8;&#x8BBF;&#x95EE;">&#x89E3;&#x51B3;&#x65B9;&#x5F0F;1&#xFF1A;&#x54CD;&#x5E94;&#x5934;&#x6DFB;&#x52A0;Header&#x5141;&#x8BB8;&#x8BBF;&#x95EE;</h3>
<p><strong>&#x8DE8;&#x57DF;&#x8D44;&#x6E90;&#x5171;&#x4EAB;&#xFF08;CORS&#xFF09;Cross-Origin Resource Sharing</strong></p>
<pre><code class="lang-java">response.addHeader(&#x2018;Access-Control-Allow-Origin:*&#x2019;);<span class="hljs-comment">//&#x5141;&#x8BB8;&#x6240;&#x6709;&#x6765;&#x6E90;&#x8BBF;&#x95EE; </span>
response.addHeader(&#x2018;Access-Control-Allow-Method:POST,GET&#x2019;);<span class="hljs-comment">//&#x5141;&#x8BB8;&#x8BBF;&#x95EE;&#x7684;&#x65B9;&#x5F0F;</span>
</code></pre>
<h3 id="&#x89E3;&#x51B3;&#x65B9;&#x5F0F;2&#xFF1A;jsonp-&#x53EA;&#x652F;&#x6301;get&#x8BF7;&#x6C42;&#x4E0D;&#x652F;&#x6301;post&#x8BF7;&#x6C42;">&#x89E3;&#x51B3;&#x65B9;&#x5F0F;2&#xFF1A;jsonp &#x53EA;&#x652F;&#x6301;get&#x8BF7;&#x6C42;&#x4E0D;&#x652F;&#x6301;post&#x8BF7;&#x6C42;</h3>
<p>&#x7528;&#x6CD5;&#xFF1A;&#x2460;dataType&#x6539;&#x4E3A;jsonp     &#x2461;jsonp : &quot;jsonpCallback&quot;&#x2014;&#x2014;&#x2014;&#x2014;&#x53D1;&#x9001;&#x5230;&#x540E;&#x7AEF;&#x5B9E;&#x9645;&#x4E3A;<a href="http://a.a.com/a/FromServlet?userName=644064" target="_blank">http://a.a.com/a/FromServlet?userName=644064</a>&amp;jsonpCallback=jQueryxxx     &#x2462;&#x540E;&#x7AEF;&#x83B7;&#x53D6;get&#x8BF7;&#x6C42;&#x4E2D;&#x7684;jsonpCallback    &#x2463;&#x6784;&#x9020;&#x56DE;&#x8C03;&#x7ED3;&#x6784;</p>
<pre><code class="lang-javascript">$.ajax({
            type : <span class="hljs-string">&quot;GET&quot;</span>,
            <span class="hljs-keyword">async</span> : <span class="hljs-literal">false</span>,
            url : <span class="hljs-string">&quot;http://a.a.com/a/FromServlet?userName=644064&quot;</span>,
            dataType : <span class="hljs-string">&quot;jsonp&quot;</span>,<span class="hljs-comment">//&#x6570;&#x636E;&#x7C7B;&#x578B;&#x4E3A;jsonp  </span>
            jsonp : <span class="hljs-string">&quot;jsonpCallback&quot;</span>,<span class="hljs-comment">//&#x670D;&#x52A1;&#x7AEF;&#x7528;&#x4E8E;&#x63A5;&#x6536;callback&#x8C03;&#x7528;&#x7684;function&#x540D;&#x7684;&#x53C2;&#x6570;</span>
            success : <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">data</span>) </span>{
                alert(data[<span class="hljs-string">&quot;userName&quot;</span>]);
            },
            error : <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
                alert(<span class="hljs-string">&apos;fail&apos;</span>);
            }
        });
</code></pre>
<pre><code class="lang-java"><span class="hljs-comment">//&#x540E;&#x7AEF;</span>
        String jsonpCallback = request.getParameter(<span class="hljs-string">&quot;jsonpCallback&quot;</span>);
        <span class="hljs-comment">//&#x6784;&#x9020;&#x56DE;&#x8C03;&#x51FD;&#x6570;&#x683C;&#x5F0F;jsonpCallback(&#x6570;&#x636E;)</span>
        resp.getWriter().println(jsonpCallback+<span class="hljs-string">&quot;(&quot;</span>+jsonObject.toJSONString()+<span class="hljs-string">&quot;)&quot;</span>);
</code></pre>
<h3 id="jsonp&#x5B9E;&#x73B0;&#x539F;&#x7406;">JSONP&#x5B9E;&#x73B0;&#x539F;&#x7406;</h3>
<blockquote>
<p>&#x5728;&#x540C;&#x6E90;&#x7B56;&#x7565;&#x4E0B;&#xFF0C;&#x5728;&#x67D0;&#x4E2A;&#x670D;&#x52A1;&#x5668;&#x4E0B;&#x7684;&#x9875;&#x9762;&#x662F;&#x65E0;&#x6CD5;&#x83B7;&#x53D6;&#x5230;&#x8BE5;&#x670D;&#x52A1;&#x5668;&#x4EE5;&#x5916;&#x7684;&#x6570;&#x636E;&#x7684;&#xFF0C;&#x5373;&#x4E00;&#x822C;&#x7684;ajax&#x662F;&#x4E0D;&#x80FD;&#x8FDB;&#x884C;&#x8DE8;&#x57DF;&#x8BF7;&#x6C42;&#x7684;&#x3002;&#x4F46; img&#x3001;iframe &#x3001;script&#x7B49;&#x6807;&#x7B7E;&#x662F;&#x4E2A;&#x4F8B;&#x5916;&#xFF0C;&#x8FD9;&#x4E9B;&#x6807;&#x7B7E;&#x53EF;&#x4EE5;&#x901A;&#x8FC7;src&#x5C5E;&#x6027;&#x8BF7;&#x6C42;&#x5230;&#x5176;&#x4ED6;&#x670D;&#x52A1;&#x5668;&#x4E0A;&#x7684;&#x6570;&#x636E;&#x3002;&#x5229;&#x7528;<script>标签的开放策略，我们可以实现跨域请求数据，当然这需要服务器端的配合。 Jquery中ajax的核心是通过 XmlHttpRequest获取非本页内容，而jsonp的核心则是动态添加<script>标签来调用服务器提供的 js脚本。</p>
<p>　　当我们正常地请求一个JSON数据的时候，服务端返回的是一串JSON类型的数据，而我们使用 JSONP模式来请求数据的时候服务端返回的是一段可执行的JavaScript代码。因为jsonp 跨域的原理就是用的动态加载<script>的src ，所以我们只能把参数通过url的方式传递,所以jsonp的 type类型只能是get ！</p>
<p>示例：</p>
<p>$.ajax({</p>
<p>​    url: &#39;<a href="http://192.168.10.46/demo/test.jsp">http://192.168.10.46/demo/test.jsp</a>&#39;,        //不同的域</p>
<p>​    type: &#39;GET&#39;,                                                        // jsonp模式只有GET 是合法的</p>
<p>​    data: {</p>
<p>​        &#39;action&#39;: &#39;aaron&#39;</p>
<p>​    },</p>
<p>​    dataType: &#39;jsonp&#39;,                                              // 数据类型</p>
<p>​    jsonp: &#39;jsonpCallback&#39;,                                     // 指定回调函数名，与服务器端接收的一致，并回传回来</p>
<p>})</p>
<p>其实jquery 内部会转化成</p>
<p><a href="http://192.168.10.46/demo/test.jsp?jsonpCallback=jQuery202003573935762227615_1402643146875&amp;action=aaron">http://192.168.10.46/demo/test.jsp?jsonpCallback=jQuery202003573935762227615_1402643146875&amp;action=aaron</a></p>
<p>然后动态加载</p>
<p>然后后端就会执行jsonpCallback(传递参数 )，把数据通过实参的形式发送出去。</p>
<p>　　使用JSONP 模式来请求数据的整个流程：客户端发送一个请求，规定一个可执行的函数名（这里就是 jQuery做了封装的处理，自动帮你生成回调函数并把数据取出来供success属性方法来调用,而不是传递的一个回调句柄），服务器端接受了这个 jsonpCallback函数名，然后把数据通过实参的形式发送出去</p>
<p>（在jquery 源码中， jsonp的实现方式是动态添加<script>标签来调用服务器提供的 js脚本。jquery 会在window对象中加载一个全局的函数，当 <script>代码插入时函数执行，执行完毕后就 <script>会被移除。同时jquery还对非跨域的请求进行了优化，如果这个请求是在同一个域名下那么他就会像正常的 Ajax请求一样工作。）</p>
</blockquote>
<h3>解决方式3：httpClient内部转发</h3>
<p>实现原理很简单，若想在B站点中通过Ajax访问A站点获取结果，固然有ajax跨域问题，但在B站点中访问B站点获取结果，不存在跨域问题，这种方式实际上是在B站点中ajax请求访问B站点的HttpClient，再通过HttpClient转发请求获取A站点的数据结果。但这种方式产生了两次请求，效率低，但内部请求，抓包工具无法分析，安全。</p>
<pre><code class="lang-javascript">$.ajax({
            type : &quot;GET&quot;,
            async : false,
            url : &quot;http://b.b.com:8080/B/FromAjaxservlet?userName=644064&quot;,
            dataType : &quot;json&quot;,
            success : function(data) {
                alert(data[&quot;userName&quot;]);
            },
            error : function() {
                alert(&#39;fail&#39;);
            }
        });
</code></pre>
<pre><code class="lang-java">@WebServlet(&quot;/FromAjaxservlet&quot;)
public class FromAjaxservlet extends HttpServlet{


    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            //创建默认连接
            CloseableHttpClient httpClient = HttpClients.createDefault();
            //创建HttpGet对象,处理get请求,转发到A站点
            HttpGet httpGet = new HttpGet(&quot;http://a.a.com:8080/A/FromServlet?userName=&quot;+req.getParameter(&quot;userName&quot;)); 
                        //执行
            CloseableHttpResponse response = httpClient.execute(httpGet);
            int code = response.getStatusLine().getStatusCode();
            //获取状态
            System.out.println(&quot;http请求结果为:&quot;+code);
            if(code == 200){
                                //获取A站点返回的结果
                String result = EntityUtils.toString(response.getEntity());
                System.out.println(result);
                                //把结果返回给B站点
                resp.getWriter().print(result);
            }
            response.close();
            httpClient.close();
        } catch (Exception e) {
        }
    }
}
</code></pre>
<h3>解决方式4：使用nginx搭建企业级接口网关方式</h3>
<p>www.a.a.com不能直接请求www.b.b.com的内容，可以通过nginx，根据同域名，但项目名不同进行区分。什么意思呢？这么说可能有点抽象。假设我们公司域名叫www.nginxtest.com</p>
<p>当我们需要访问www.a.a.com通过www.nginxtest.com/A访问，并通过nginx转发到www.a.a.com</p>
<p>当我们需要访问www.b.b.com通过www.nginxtest.com/B访问，并通过nginx转发到www.a.a.com</p>
<p>我们访问公司的域名时，是&quot;同源&quot;的，只是项目名不同，此时项目名的作用只是为了区分，方便转发。如果你还不理解的话，先看看我是怎么进行配置的：</p>
<pre><code>server {
        listen       80;
        server_name  www.nginxtest.com;
        location /A {
            proxy_pass  http://a.a.com:81;
            index  index.html index.htm;
        }
        location /B {
            proxy_pass  http://b.b.com:81;
            index  index.html index.htm;
        }
    }
</code></pre><p>我们访问以www.nginxtest.com开头且端口为80的网址，nginx将会进行拦截匹配，若项目名为A，则分发到a.a.com:81。实际上就是通过&quot;同源&quot;的域名，不同的项目名进行区分，通过nginx拦截匹配，转发到对应的网址。整个过程，两次请求，第一次请求nginx服务器，第二次nginx服务器通过拦截匹配分发到对应的网址。</p>
<h3>解决方式5：使用Spring Cloud zuul接口网关</h3>
</script></p></blockquote>
                                
                                </section>
                            
    </div>
    <div class="search-results">
        <div class="has-results">
            
            <h1 class="search-results-title"><span class='search-results-count'></span> results matching "<span class='search-query'></span>"</h1>
            <ul class="search-results-list"></ul>
            
        </div>
        <div class="no-results">
            
            <h1 class="search-results-title">No results matching "<span class='search-query'></span>"</h1>
            
        </div>
    </div>
</div>

                        </div>
                    </div>
                
            </div>

            
                
                <a href="获取当前地址坐标.html" class="navigation navigation-prev " aria-label="Previous page: 获取当前地址坐标">
                    <i class="fa fa-angle-left"></i>
                </a>
                
                
                <a href="解决vue-cli webpack打包后加载资源的路径问题.html" class="navigation navigation-next " aria-label="Next page: 解决vue-cli webpack打包后加载资源的路径问题">
                    <i class="fa fa-angle-right"></i>
                </a>
                
            
        
    </div>

    <script>
        var gitbook = gitbook || [];
        gitbook.push(function() {
            gitbook.page.hasChanged({"page":{"title":"解决ajax跨域问题【5种解决方案】","level":"1.33","depth":1,"next":{"title":"解决vue-cli webpack打包后加载资源的路径问题","level":"1.34","depth":1,"path":"project/解决vue-cli webpack打包后加载资源的路径问题.md","ref":"project/解决vue-cli webpack打包后加载资源的路径问题.md","articles":[]},"previous":{"title":"获取当前地址坐标","level":"1.32","depth":1,"path":"project/获取当前地址坐标.md","ref":"project/获取当前地址坐标.md","articles":[]},"dir":"ltr"},"config":{"gitbook":"*","theme":"default","variables":{},"plugins":[],"pluginsConfig":{"highlight":{},"search":{},"lunr":{"maxIndexSize":1000000,"ignoreSpecialCharacters":false},"sharing":{"facebook":true,"twitter":true,"google":false,"weibo":false,"instapaper":false,"vk":false,"all":["facebook","google","twitter","weibo","instapaper"]},"fontsettings":{"theme":"white","family":"sans","size":2},"theme-default":{"styles":{"website":"styles/website.css","pdf":"styles/pdf.css","epub":"styles/epub.css","mobi":"styles/mobi.css","ebook":"styles/ebook.css","print":"styles/print.css"},"showLevel":false}},"structure":{"langs":"LANGS.md","readme":"README.md","glossary":"GLOSSARY.md","summary":"SUMMARY.md"},"pdf":{"pageNumbers":true,"fontSize":12,"fontFamily":"Arial","paperSize":"a4","chapterMark":"pagebreak","pageBreaksBefore":"/","margin":{"right":62,"left":62,"top":56,"bottom":56}},"styles":{"website":"styles/website.css","pdf":"styles/pdf.css","epub":"styles/epub.css","mobi":"styles/mobi.css","ebook":"styles/ebook.css","print":"styles/print.css"}},"file":{"path":"project/解决ajax跨域问题【5种解决方案】.md","mtime":"2019-06-19T16:24:05.165Z","type":"markdown"},"gitbook":{"version":"3.2.3","time":"2019-07-18T03:07:23.077Z"},"basePath":"..","book":{"language":""}});
        });
    </script>
</div>

        
    <script src="../gitbook/gitbook.js"></script>
    <script src="../gitbook/theme.js"></script>
    
        
        <script src="../gitbook/gitbook-plugin-search/search-engine.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-search/search.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-lunr/lunr.min.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-lunr/search-lunr.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-sharing/buttons.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-fontsettings/fontsettings.js"></script>
        
    

    </body>
</html>

